import React from 'react';
import { 
    List,
    Datagrid, 
    TextField, 
    ReferenceField, 
    EditButton, 
    Edit, 
    DisabledInput, 
    ReferenceInput, 
    SelectInput, 
    TextInput, 
    LongTextInput, 
    SimpleForm,
    Create,
    Filter,
    Responsive,
    SimpleList,
    AutocompleteInput
} from 'react-admin';
import RealTime from './realtime';
import { withStyles } from '@material-ui/core/styles';

const styles = {
    button: {
        fontWeight: 'bold',
        // This is JSS syntax to target a deeper element using css selector, here the svg icon for this button
        '& svg': { color: 'orange' }
    },
};

const MyEditButton = withStyles(styles)(({ classes, ...props }) => (
    <EditButton
        className={classes.button}
        {...props}
    />
));

const PostFilter = (props) => (
    <Filter {...props}>
        <TextInput label="Search" source="q" alwaysOn />
        <ReferenceInput label="User" source="author" reference="users" allowEmpty>
            <SelectInput optionText="username" />
        </ReferenceInput>
    </Filter>
);

export const PostList = props => (
    <RealTime source="posts">
    <List  filters={<PostFilter />}  {...props}>
        <Responsive
            small={
                <SimpleList
                    primaryText={record => record.title}
                    secondaryText={record => `${record.breif} views`}
                    tertiaryText={record => new Date(record.createdAt).toLocaleDateString()}
                />
            }
            medium={
                <Datagrid>
                    <TextField source="id" />
                    <ReferenceField label="创作人" source="author" reference="users">
                        <TextField source="username" />
                    </ReferenceField>
                    <TextField source="title" />
                    <TextField source="body" />
                    <MyEditButton />
                </Datagrid>
            }
        />
    </List>
    </RealTime>
);
const PostTitle = ({ record }) => {
        return <span>Post {record ? `"${record.title}"` : ''}</span>;
};

export const PostEdit = props => (
    <Edit title={<PostTitle />} {...props}>
        <SimpleForm>
              <DisabledInput source="id" />
            <ReferenceInput source="author" reference="users">
               <SelectInput optionText="username" />
            </ReferenceInput>
           <TextInput source="title" />
           <LongTextInput source="body" />
        </SimpleForm>
    </Edit>
);

export const PostCreate = props => (
    <Create {...props}>
        <SimpleForm>
            <ReferenceInput label="作者" reference="users" source="author">
                <AutocompleteInput  optionText="username" />
            </ReferenceInput>
            <TextInput source="title" />
            <LongTextInput source="body" />
        </SimpleForm>
    </Create>
);